import { logger } from '../logger.js';
import request from '../request.js';
import { AxiosError } from 'axios';

interface Auth {
  userName: String;
  mail: String;
  displayName: String;
  cn: String;
  roles: String[];
  uiConfig: String;
  productViewDepartment: String;
}

const verifyTokenService = async (authorization: string): Promise<Auth> => {
  let response;
  try {
    response = await request.post(
      process.env.WEBHOOK_URL_AUTH,
      {},
      {
        headers: {
          authorization,
        },
      },
    );
    if (response.data.success) {
      return response.data;
    } else {
      throw new Error('Token verification failed');
    }
  } catch (e) {
    logger.error(`verify auth token failed: ${(e as AxiosError).response}`);
    throw new Error('Not authorized!');
  }
};

export default verifyTokenService;
